import axios from 'axios'

class GoogleTranslateService {
  constructor() {
    this.apiKey = process.env.VUE_APP_GOOGLE_TRANSLATE_API_KEY || 'AIzaSyDNeFm8A-c5Nv0hDxlYAK0hnf2L_O3tw2I'
    this.baseURL = 'https://translation.googleapis.com/language/translate/v2'
    this.maxBatchSize = 100 // Google Translate API 单次请求的最大文本数量
  }

  async translateText(text, targetLang = 'en', sourceLang = 'zh') {
    try {
      // 构建请求参数，如果sourceLang为'auto'则不传source参数
      const params = {
        q: text,
        target: targetLang,
        format: 'text'
      }
      
      // 只有当sourceLang不是'auto'时才添加source参数
      if (sourceLang && sourceLang !== 'auto') {
        params.source = sourceLang
      }
      
      const response = await axios.post(`${this.baseURL}?key=${this.apiKey}`, params)
      
      return response.data.data.translations[0].translatedText
    } catch (error) {
      console.error('Translation error:', error)
      return text // 返回原文本作为fallback
    }
  }

  async translateObject(obj, targetLang = 'en', sourceLang = 'zh') {
    const translated = {}
    for (const [key, value] of Object.entries(obj)) {
      if (typeof value === 'string') {
        translated[key] = await this.translateText(value, targetLang, sourceLang)
      } else {
        translated[key] = value
      }
    }
    return translated
  }

  // 批量翻译单个批次
  async _translateBatch(texts, targetLang = 'en', sourceLang = 'zh') {
    try {
      // 构建请求参数
      const params = {
        q: texts,
        target: targetLang,
        format: 'text'
      }
      
      // 只有当sourceLang不是'auto'时才添加source参数
      if (sourceLang && sourceLang !== 'auto') {
        params.source = sourceLang
      }
      
      const response = await axios.post(`${this.baseURL}?key=${this.apiKey}`, params)
      
      return response.data.data.translations.map(t => t.translatedText)
    } catch (error) {
      console.error('Batch translation error:', error)
      return texts // 翻译失败时返回原文本
    }
  }

  // 批量翻译，支持大量文本分批处理
  async batchTranslate(texts, targetLang = 'en', sourceLang = 'zh') {
    try {
      // 如果文本数量小于最大批次大小，直接翻译
      if (texts.length <= this.maxBatchSize) {
        return await this._translateBatch(texts, targetLang, sourceLang)
      }
      
      // 将文本分批处理
      const batches = []
      for (let i = 0; i < texts.length; i += this.maxBatchSize) {
        batches.push(texts.slice(i, i + this.maxBatchSize))
      }
      
      console.log(`将 ${texts.length} 个文本分成 ${batches.length} 批进行翻译`)
      
      // 依次翻译每个批次
      const results = []
      for (let i = 0; i < batches.length; i++) {
        console.log(`正在翻译第 ${i + 1}/${batches.length} 批，包含 ${batches[i].length} 个文本`)
        const batchResults = await this._translateBatch(batches[i], targetLang, sourceLang)
        results.push(...batchResults)
      }
      
      return results
    } catch (error) {
      console.error('Batch translation error:', error)
      return texts // 翻译失败时返回原文本
    }
  }
}

export default new GoogleTranslateService()